'use strict';

/*
{ id: '65f1aeb1f08210b07ddc34fb',
  payTitle: '周会员',
  openId: 'o4wT_7KQwjnWrrugGmgC1NlAdWKc',
  mchId: '1667323158',
  key: '3C7B53918728417C45D12E6D45FB2CD7',
  orderId: 1710337710689,
  orderType: 3,
  payPrice: 3800,
  creatTime: '2024-03-13 21:48:30' }
*/
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	const db = uniCloud.database();
	const collection = db.collection('payOrderInfo');
	let res = {};
	if(event.id){
		let countRes = await collection.where({"orderId":event.orderId}).count();
		console.log('count : ', countRes)
		if(countRes.total>0){
			const userCollection = db.collection('users');
			let userRes = await userCollection.where({"openId":event.openId}).get();
			console.log('user : ', userRes)
			let userInfo = {};
			if(userRes.data.length>0){
				userInfo = userRes.data[0];
				let currentTime = new Date().getTime();
				let addTime = 0;
				if(event.orderType === 1||event.orderType === 11){
					addTime = 99 * 366 * 24 * 60 * 60 * 1000;
				}else if(event.orderType === 2||event.orderType === 12){
					addTime = 366 * 24 * 60 * 60 * 1000;
				}else if(event.orderType === 3||event.orderType === 13){
					addTime = 31 * 24 * 60 * 60 * 1000;
				}
				if(userInfo.expireDate>currentTime){
					let totalTime = userInfo.expireDate + addTime;
					let uploadRes = await userCollection.doc(userInfo._id).update({
						expireDate:totalTime,
						 orderId: event.orderId,
						 orderType:event.orderType
					});
					console.log('uploadUserres : ', uploadRes)
					if(uploadRes.updated === 1){
						res = {"code":100,"msg":"支付成功！"}
					}else{
						res = {"code":103,"msg":"更新用户订单信息异常，请点击恢复购买按钮"}
					}
				}else{
					let totalTime = currentTime + addTime;
					let uploadRes = await userCollection.doc(userInfo._id).update({
						expireDate:totalTime
					});
					console.log('uploadUserres : ', uploadRes)
					if(uploadRes.updated === 1){
						res = {"code":100,"msg":"支付成功！"}
					}else{
						res = {"code":103,"msg":"更新用户订单信息异常，请点击恢复购买按钮"}
					}
				}
			}else{
				res = {"code":104,"msg":"不是有效用户,请重试"}
			}
			
		}else{
			res = {"code":102,"msg":"订单信息不存在，请重试"}
		}
	}else{
		res = {"code":101,"msg":"订单信息为空，请重试"}
	}
	
	//返回数据给客户端
	return res;
};
